package cn.agiledata.bank.linkbank.impl;

import java.util.HashMap;
import java.util.Map;

import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.logic.payment.BankPayRequest;

/**
 * 默认的抽象银行支付请求实现
 * 
 * @author 马贤波
 * 
 */
public abstract class AbstractBankPayRequest implements BankPayRequest {

    private String bankUrl;

    private Map parameters;

    private boolean valid;

    private boolean supported;

    protected AbstractBankPayRequest() {
        this.parameters = new HashMap();
        this.valid = true;
        this.supported = true; // 默认被支持
    }

    public final void setBankUrl(String bankUrl) {
        this.bankUrl = bankUrl;
    }

    public final String getBankUrl() {
        return this.bankUrl;
    }

    /**
     * 获取有效的请求参数关键字，只有有效的参数才会提交给银行，若该方法返回null，则提交所有参数给银行
     * 
     * @return 有效的请求参数关键字
     */
    protected String[] getValidKeys() {
        return null;
    }

    public final Map getParameters() {
        String[] keys = getValidKeys();
        if (keys == null) {
            return this.parameters;
        }
        Map params = new HashMap();
        for (int i = 0; i < keys.length; i++) {
            params.put(keys[i], this.parameters.get(keys[i]));
        }
        return params;
    }

    protected final String getParameter(String name) {
        return (String) this.parameters.get(name);
    }

    /**
     * 设置参数
     * 
     * @param name
     *            参数名
     * @param value
     *            参数值
     */
    protected final void setParameter(String name, String value) {
        if (value != null)
            this.parameters.put(name, value);
    }

    public final boolean isValid() {
        return this.valid;
    }

    public final void setValid(boolean valid) {
        this.valid = valid;
    }

    public final boolean isSupported() {
        return this.supported;
    }

    public final void setSupported(boolean supported) {
        this.supported = supported;
    }

    public String getSubmitMethod() {
        return SUBMIT_METHOD_POST; // 默认以POST方式提交请求数据
    }

    public void prepare() throws LinkBankException {
    }

    public final BankPayRequest copy() {
        AbstractBankPayRequest request = getCopiedInstance();
        request.bankUrl = this.bankUrl;
        request.parameters = new HashMap(this.parameters);
        request.valid = this.valid;
        return request;
    }

    /**
     * 
     * @return 复制出的AbstractBankPayRequest实例
     */
    protected abstract AbstractBankPayRequest getCopiedInstance();

}